<template>
  <!-- 产品检测COA单主页面 -->
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <!-- <el-form-item label="检测COA单号" prop="coaNum">
        <el-input
          v-model="queryParams.coaNum"
          placeholder="请输入检测COA单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" @click="handleUpload"> 上传</el-button>
        <!-- <el-button class="custom-blue-button" @click="resetQuery"> 下载</el-button> -->
        <!-- <el-button class="custom-blue-button" @click="resetQuery"> 删除</el-button> -->
        <el-button 
          class="custom-blue-button" 
          @click="handleBatchDelete" 
          :disabled="selectedRows.length === 0"
        >
          删除
        </el-button>
        <!-- <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['business:prod-coa:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['business:prod-coa:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button> -->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" align="center" width="60">
        <template #default="scope">
          {{ (queryParams.pageNo - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="检测COA单号" align="center" prop="coaNum">
        <template #default="scope">
          <el-link type="primary" @click="handleCoaNumClick(scope.row)">
            {{ scope.row.coaNum }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="检测日期" align="center" prop="coaDate" :formatter="formatCoaDate" />
      <el-table-column label="类型" align="center" prop="type" />
      <el-table-column label="上传人" align="center" prop="creator" />
      <el-table-column
        label="上传时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            class="table-action-button"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['business:prod-coa:update']"
          >
            编辑
          </el-button>
          <el-button
            class="table-action-button delete-button"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['business:prod-coa:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ProdCoaForm ref="formRef" @success="getList" />

  <!-- 新增上传弹窗 -->
  <ProdCoaUploadForm ref="uploadFormRef" @success="getList" />

  <!-- PDF预览弹窗 -->
  <PdfPreview ref="pdfPreviewRef" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { ProdCoaApi, ProdCoaVO } from '@/api/product/prodcoa'
import ProdCoaForm from './ProdCoaForm.vue'

import { ElLoading } from 'element-plus'
import PdfPreview from '@/components/PdfPreview.vue'

import ProdCoaUploadForm from './ProdCoaUploadForm.vue'
// 上传弹窗引用
const uploadFormRef = ref()
// PDF预览弹窗引用
const pdfPreviewRef = ref()

/** 上传按钮操作 */
const handleUpload = () => {
  uploadFormRef.value.open()
}

/** 产品coa 列表 */
defineOptions({ name: 'ProdCoa' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ProdCoaVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  coaNum: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ProdCoaApi.getProdCoaPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

// 添加选中行的响应式变量
const selectedRows = ref<ProdCoaVO[]>([])

// 处理表格选择变化
const handleSelectionChange = (selection: ProdCoaVO[]) => {
  selectedRows.value = selection
}

// 批量删除操作
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    message.warning('请至少选择一条记录')
    return
  }

  try {
    // 删除的二次确认
    await message.delConfirm(`确定要删除选中的 ${selectedRows.value.length} 条记录吗？`)
    
    // 显示删除进度
    const loading = ElLoading.service({
      text: '正在删除...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    
    try {
      // 循环调用单个删除接口
      const deletePromises = selectedRows.value.map(row => 
        ProdCoaApi.deleteProdCoa(row.id)
      )
      
      // 等待所有删除操作完成
      await Promise.all(deletePromises)
      
      message.success(t('common.delSuccess'))
      
      // 清空选中状态
      selectedRows.value = []
      
      // 刷新列表
      await getList()
    } finally {
      loading.close()
    }
  } catch (error) {
    // 错误处理由message.delConfirm处理
  }
}

/** 单行删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ProdCoaApi.deleteProdCoa(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** COA单号点击事件 */
// const handleCoaNumClick = async (id: number) => {
//   try {
//     const response = await ProdCoaApi.getProdCoaForUrl(id)
//     if (response) {
//       // 在新窗口中打开URL
//       window.open(response, '_blank')
//     } else {
//       message.warning('未找到相关链接')
//     }
//   } catch (error) {
//     message.error('获取链接失败')
//     console.error('获取COA链接失败:', error)
//   }
// }
const handleCoaNumClick = async (row: ProdCoaVO) => {
  try {
    // 显示加载提示
    const loadingInstance = ElLoading.service({
      text: '正在加载PDF文件...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    const response = await ProdCoaApi.getProdCoaForUrl(row.id)

    loadingInstance.close()

    if (response) {
      // 打开PDF预览弹窗
      pdfPreviewRef.value.open(response, `COA单号: ${row.coaNum}`)
    } else {
      message.warning('未找到相关PDF文件')
    }
  } catch (error) {
    ElLoading.service().close()
    message.error('获取PDF文件失败')
    console.error('获取COA链接失败:', error)
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ProdCoaApi.exportProdCoa(queryParams)
    download.excel(data, '产品报价.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const formatCoaDate = (row: any, column: any, cellValue: any) => {
  console.log('原始日期数据:', cellValue, typeof cellValue) // 添加调试信息

  if (!cellValue) return ''

  // 如果是数组格式的日期
  if (Array.isArray(cellValue)) {
    const [year, month, day] = cellValue
    // 确保 month 和 day 是两位数
    const formattedMonth = String(month).padStart(2, '0')
    const formattedDay = String(day).padStart(2, '0')
    return `${year}-${formattedMonth}-${formattedDay}`
  }

  // 如果是日期字符串格式，直接格式化
  if (typeof cellValue === 'string') {
    // 处理 "2025,7,23" 这样的格式
    if (cellValue.includes(',')) {
      const [year, month, day] = cellValue.split(',').map(Number)
      const formattedMonth = String(month).padStart(2, '0')
      const formattedDay = String(day).padStart(2, '0')
      return `${year}-${formattedMonth}-${formattedDay}`
    }

    // 处理 "2025723" 这样的格式（看起来像你现在遇到的情况）
    if (/^\d{7,8}$/.test(cellValue)) {
      let year, month, day
      if (cellValue.length === 7) {
        year = cellValue.substring(0, 4)
        month = cellValue.substring(4, 5)
        day = cellValue.substring(5)
        // 判断是 YYYYMDD 还是 YYYYMMD
        if (day.length > 2) {
          day = cellValue.substring(5, 7)
          month = cellValue.substring(4, 5)
        } else {
          month = cellValue.substring(4, 5)
        }
      } else if (cellValue.length === 8) {
        year = cellValue.substring(0, 4)
        month = cellValue.substring(4, 6)
        day = cellValue.substring(6)
      }

      return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
    }

    // 处理其他日期格式
    const date = new Date(cellValue)
    if (!isNaN(date.getTime())) {
      return (
        date.getFullYear() +
        '-' +
        String(date.getMonth() + 1).padStart(2, '0') +
        '-' +
        String(date.getDate()).padStart(2, '0')
      )
    }
  }

  // 如果是日期对象
  if (cellValue instanceof Date) {
    return (
      cellValue.getFullYear() +
      '-' +
      String(cellValue.getMonth() + 1).padStart(2, '0') +
      '-' +
      String(cellValue.getDate()).padStart(2, '0')
    )
  }

  console.log('未处理的格式，直接返回:', cellValue) // 调试信息
  return cellValue
}

onUnmounted(() => {
  // 清理状态或取消订阅等
  loading.value = false
  list.value = []
  total.value = 0
  queryParams.coaNum = undefined
})

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style scoped>
.custom-blue-button {
  color: #4da6ff; /* 字体颜色 */
  border-color: #4da6ff; /* 边框颜色 */
}

.custom-blue-button:hover {
  color: darkblue; /* 悬停时字体颜色 */
  border-color: darkblue; /* 悬停时边框颜色 */
}

/* 表格操作按钮样式 */
.table-action-button {
  color: #409eff;
  border-color: #409eff;
  padding: 4px 8px;
  font-size: 12px;
}

.table-action-button:hover {
  color: #fff;
  background-color: #409eff;
}

.delete-button {
  margin-left: 8px;
}
</style>
